<script setup>
import { onMounted, ref } from 'vue'
import * as echarts from 'echarts'
import 'echarts-wordcloud' // 需要安装这个包用于词云展示
import { getEmailList } from '@/api/email.js'
import { ElMessage } from 'element-plus'

// 定义多个图表容器的引用
const wordCloudNormalRef = ref(null)
const wordCloudSpamRef = ref(null)
const lengthDistRef = ref(null)

// 在 script setup 顶部添加 lengthDistData 的定义
const lengthDistData = ref({
  categories: [],
  normal: [],
  spam: []
})

// 从邮件内容中提取关键词并统计频率
const extractKeywords = (emails) => {
  // 分别存储正常邮件和垃圾邮件的词频
  const normalWordFreq = new Map()
  const spamWordFreq = new Map()
  
  emails.forEach(email => {
    // 获取邮件内容
    const content = email.processed_content
    
    // 简单的分词（按空格分割，因为processed_content已经预处理过）
    const words = content.split(/\s+/)
    
    // 过滤掉停用词、数字和长度过短的词
    const filteredWords = words.filter(word => 
      word.length > 3 && 
      !/^\d+$/.test(word) && 
      !stopWords.includes(word.toLowerCase())
    )
    
    // 根据邮件类型统计词频
    const wordFreq = email.status === "1" ? normalWordFreq : spamWordFreq
    filteredWords.forEach(word => {
      wordFreq.set(word, (wordFreq.get(word) || 0) + 1)
    })
  })
  
  // 转换为词云数据格式
  const convertToWordCloudData = (wordFreq) => {
    return Array.from(wordFreq.entries())
      .sort((a, b) => b[1] - a[1])
      .slice(0, 50)  // 取前50个高频词
      .map(([name, value]) => ({ 
        name, 
        value: Math.log(value + 1) * 20  // 使用对数缩放使数值差异不要太大
      }))
  }
  
  return {
    normalWordCloudData: convertToWordCloudData(normalWordFreq),
    spamWordCloudData: convertToWordCloudData(spamWordFreq)
  }
}

// 常用英文停用词列表（保留一些可能有意义的词）
const stopWords = [
  'the', 'be', 'to', 'of', 'and', 'a', 'in', 'that', 'have',
  'it', 'for', 'on', 'with', 'he', 'as', 'you', 'do', 'at',
  'this', 'but', 'his', 'by', 'from', 'they', 'we', 'say',
  'or', 'an', 'will', 'would', 'there', 'what', 'so', 'up',
  'out', 'if', 'about', 'get', 'which', 'go', 'me', 'when',
  'can', 'like', 'time', 'no', 'just', 'him', 'know', 'take',
  'into', 'year', 'your', 'some', 'could', 'them', 'see',
  'than', 'then', 'now', 'look', 'only', 'come', 'its', 'over',
  'think', 'also', 'back', 'after', 'use', 'two', 'how', 'our',
  'work', 'first', 'well', 'way', 'even', 'new', 'want'
]

// 修改获取邮件数据并处理的方法
const fetchAndProcessEmails = async () => {
  try {
    const result = await getEmailList()
    if (result.status === 'success') {
      const { normalWordCloudData, spamWordCloudData } = extractKeywords(result.emails)
      
      // 处理邮件长度分布数据
      const lengthRanges = {}
      result.emails.forEach(email => {
        const length = email.processed_content.length
        const range = Math.floor(length / 100) * 100
        if (!lengthRanges[range]) {
          lengthRanges[range] = { normal: 0, spam: 0 }
        }
        if (email.status === "1") {
          lengthRanges[range].normal++
        } else {
          lengthRanges[range].spam++
        }
      })

      // 转换数据格式
      const sortedRanges = Object.keys(lengthRanges).sort((a, b) => Number(a) - Number(b))
      lengthDistData.value = {
        categories: sortedRanges.map(range => `${range}-${Number(range) + 100}`),
        normal: sortedRanges.map(range => lengthRanges[range].normal),
        spam: sortedRanges.map(range => lengthRanges[range].spam)
      }
      
      // 初始化词云图
      initWordCloud(wordCloudNormalRef.value, normalWordCloudData, '正常邮件关键词分布')
      initWordCloud(wordCloudSpamRef.value, spamWordCloudData, '垃圾邮件关键词分布')
      // 初始化长度分布图
      initLengthDist()
    } else {
      ElMessage.error(result.message || '获取邮件列表失败')
    }
  } catch (error) {
    ElMessage.error('获取邮件列表失败')
    console.error('获取邮件数据失败:', error)
  }
}

// 初始化词云图
const initWordCloud = (ref, data, title) => {
  const chart = echarts.init(ref)
  const option = {
    title: {
      text: title,
      left: 'center',
      top: 20,
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      show: true,
      formatter: function(params) {
        return `${params.name}: ${Math.round(Math.exp(params.value / 20) - 1)}次`  // 反向计算原始词频
      }
    },
    series: [{
      type: 'wordCloud',
      shape: 'circle',
      left: 'center',
      top: 'center',
      width: '90%',
      height: '90%',
      right: null,
      bottom: null,
      sizeRange: [12, 50],
      rotationRange: [-45, 45],
      rotationStep: 15,
      gridSize: 8,
      drawOutOfBound: false,
      layoutAnimation: true,
      data: data,
      textStyle: {
        fontFamily: 'sans-serif',
        fontWeight: 'bold',
        color: function () {
          return 'rgb(' + [
            Math.round(100 + Math.random() * 100),
            Math.round(100 + Math.random() * 100),
            Math.round(150 + Math.random() * 50)
          ].join(',') + ')'
        }
      },
      emphasis: {
        focus: 'self',
        textStyle: {
          shadowBlur: 10,
          shadowColor: '#333',
          fontSize: 20
        }
      }
    }]
  }
  chart.setOption(option)
}

// 调整长度分布图的配置
const initLengthDist = () => {
  const chart = echarts.init(lengthDistRef.value)
  const option = {
    title: {
      text: '邮件长度分布',
      left: 'center',
      top: 30,
      textStyle: {
        fontSize: 16,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    legend: {
      data: ['正常邮件', '垃圾邮件'],
      top: 70,
      left: 'center'
    },
    grid: {
      left: '5%',
      right: '5%',
      top: '120',
      bottom: '10%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      data: lengthDistData.value.categories,
      axisLabel: {
        interval: 0,
        rotate: 0
      }
    },
    yAxis: {
      type: 'value',
      name: '邮件数量',
      nameGap: 30,
      splitLine: {
        lineStyle: {
          type: 'dashed'
        }
      }
    },
    series: [
      {
        name: '正常邮件',
        type: 'bar',
        data: lengthDistData.value.normal,
        itemStyle: {
          color: '#91cc75'
        },
        barGap: '30%',
        barCategoryGap: '20%'
      },
      {
        name: '垃圾邮件',
        type: 'bar',
        data: lengthDistData.value.spam,
        itemStyle: {
          color: '#ee6666'
        }
      }
    ]
  }
  chart.setOption(option)
}

// 组件挂载后初始化所有图表
onMounted(() => {
  fetchAndProcessEmails()
  
  // 响应式调整
  window.addEventListener('resize', () => {
    const charts = [
      wordCloudNormalRef.value,
      wordCloudSpamRef.value,
      lengthDistRef.value
    ].map(ref => echarts.getInstanceByDom(ref))
    
    charts.forEach(chart => chart?.resize())
  })
})
</script>

<template>
  <div class="statistics-container">
    <div class="chart-wrapper">
      <!-- 词云图 -->
      <div class="word-clouds">
        <div ref="wordCloudNormalRef" class="chart-item cloud-chart"></div>
        <div ref="wordCloudSpamRef" class="chart-item cloud-chart"></div>
      </div>
      
      <!-- 长度分布图 -->
      <div ref="lengthDistRef" class="chart-item dist-chart"></div>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.statistics-container {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7ff 0%, #ffffff 100%);
  min-height: 100vh;
  
  .chart-wrapper {
    max-width: 1400px;
    margin: 0 auto;
    
    .chart-item {
      background: white;
      border-radius: 12px;
      box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
      transition: all 0.3s ease;
      margin-bottom: 30px;
      
      &:hover {
        transform: translateY(-5px);
        box-shadow: 0 8px 30px rgba(0, 0, 0, 0.12);
      }
    }
    
    .word-clouds {
      display: flex;
      gap: 30px;
      margin-bottom: 30px;
      
      .cloud-chart {
        flex: 1;
        height: 400px;
      }
    }
    
    .dist-chart {
      height: 400px;
    }
  }
}
</style>